﻿using AutoMapper;
using MediatR;
using Traceability.Doamin;
using Traceability.ErrorCode;
using Traceability.Infratruvture.Interfares;
using Traceability.Write.Api.Application.Command.CommodityCommand;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Traceability.Write.Api.Application.CommandHander.CommodityHander
{
    public class DatchDelCommodityHander : IRequestHandler<DatchDelCommodityCommand, ApiResult<int>>
    {
        private readonly IMapper mapper;
        private readonly IBaseRequsitory<Commodity> baseRequsitory;

        public DatchDelCommodityHander(IMapper mapper, IBaseRequsitory<Commodity> baseRequsitory)
        {
            this.mapper = mapper;
            this.baseRequsitory = baseRequsitory;
        }

        /// <summary>
        /// 批量删除商品操作
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(DatchDelCommodityCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            // 解析 Ids 字符串为整数数组
            var ids = request.Ids.Split(',')
                                 .Select(int.Parse) 
                                 .ToArray();

            // 根据 Ids 查询对应的 Commodity 记录
            var commoditiesToDelete = baseRequsitory.GetAll()
                                                    .Where(c => ids.Contains(c.CommodityId))
                                                    .ToList();

            if (commoditiesToDelete.Count > 0)
            {
                // 批量删除记录
                foreach (var commodity in commoditiesToDelete)
                {
                    baseRequsitory.Del(commodity);
                }

                result.Code = ApiEnum.删除成功;
                result.Msg = ApiEnum.删除成功.ToString();
                result.Data = commoditiesToDelete.Count;
            }
            else
            {
                result.Code = ApiEnum.名称重复;
                result.Msg = ApiEnum.名称重复.ToString();
                result.Data = 0;
            }

            return result;
        }
    }
}